#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QTimerEvent>
#include <QMessageBox>

#include <thread>
#include "serial.h"
#include "lcd.h"
#include "xbee.h"
#include "system.h"


void runXbee(Xbee *_pXbee)
{
    _pXbee->run();
}


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    m_ui(new Ui::MainWindow),
    m_hTextUpdate(-1),
    m_pXbee(NULL),
    m_pLcd(NULL)
{
    // setup UI
    m_ui->setupUi(this);

    // setup streams
    Serial *pXbeeStream = new Serial("/dev/ttyUSB0", 57600);
    if (pXbeeStream->operational() == false)
    {
        QMessageBox::warning(NULL, "Xbee Stream Error", QString::fromStdString(pXbeeStream->error()));
    }
    else
    {
        m_pXbee = new Xbee(pXbeeStream);
        new std::thread(runXbee, m_pXbee);
    }

    Serial *pLcdStream = new Serial("/dev/ttyUSB1", 9600);
    if (pLcdStream->operational() == false)
    {
        QMessageBox::warning(NULL, "LCD Stream Error", QString::fromStdString(pLcdStream->error()));
    }
    else
    {
        m_pLcd = new Lcd(pLcdStream, 48, 64);
        m_pLcd->setBacklight(15);
    }

    // start UI
    m_hTextUpdate = startTimer(100);
}


MainWindow::~MainWindow()
{
    m_pXbee->stop();
    SYSTEM::sleep(1000);

    delete m_pXbee;
    delete m_pLcd;
    delete m_ui;
}


void MainWindow::timerEvent(QTimerEvent *_pEvent)
{
    if (m_hTextUpdate == _pEvent->timerId())
    {
        std::string ln = m_pXbee->popString();
        if (ln.length() > 0)
        {
            m_ui->textBrowser->append(QString::fromStdString(ln));

            m_pLcd->writeLine("%s", ln.c_str());
        }

        m_pLcd->blink();
    }
}
